package com.bestillet.kyllingogco;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Locale;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.AsyncTask.Status;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.support.v4.widget.DrawerLayout;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {
	private ArrayList<Card> cards;
	
	private DrawerLayout layout;
	private ListView list;
	private ImageView image;
	private TextView message, restaurant, address, hours, open, header, text, obs;
	private Button proceed, back, home, settings;
	private Context context;

	private SharedPreferences preferences;
	private ShopApplication app;
	private LoadingDialog loading;
	private BasketIdTask bTask;
	private CampaignTask cTask;
	private ImageTask iTask;
	private Campaign campaign;
	private Shop shop;
	
	private String[] items;
	
	private int basketId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		preferences = getSharedPreferences("Kylling & Co", MODE_PRIVATE);
		app = (ShopApplication) getApplicationContext();
		context = this;
		
		cards = app.getCards();
		shop = getIntent().getParcelableExtra("shop");
		
		items = new String[3 + cards.size()];
		items[0] = "Info";
		items[1] = "Indstillinger";
		items[2] = "Genbestil ordre";
		for (int i = 0; i < cards.size(); i++)
			items[3 + i] = cards.get(i).getName();
		
		layout = (DrawerLayout) findViewById(R.id.drawer_layout);
        list = (ListView) findViewById(R.id.left_drawer);
        
        list.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, items));
        list.setOnItemClickListener(new DrawerItemClickListener());
		
		image = (ImageView) findViewById(R.id.imgCampaign);
		message = (TextView) findViewById(R.id.lblMessage);
		restaurant = (TextView) findViewById(R.id.lblRestaurant);
		address = (TextView) findViewById(R.id.lblAddress);
		hours = (TextView) findViewById(R.id.lblHours);
		open = (TextView) findViewById(R.id.lblOpen);
		header = (TextView) findViewById(R.id.lblCampaignHeader);
		text = (TextView) findViewById(R.id.lblCampaignText);
		obs = (TextView) findViewById(R.id.lblCampaignObs);
		
		proceed = (Button) findViewById(R.id.btnContinue);
		proceed.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(v.getContext(), CategoryActivity.class);
				startActivity(intent);
			}
		});
		
		back = (Button) findViewById(R.id.btnBack);
		back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		home = (Button) findViewById(R.id.btnHome);
		home.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		settings = (Button) findViewById(R.id.btnSettings);
		settings.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//openOptionsMenu();
				//invalidateOptionsMenu();
				layout.openDrawer(list);
			}
		});

		loading = new LoadingDialog(this);
		loading.show();
		
		if (shop.getHours().equals("Lukket") || shop.getOrders().equals("Lukket")) {
			iTask = new ImageTask();
			iTask.execute();
		} else {
			cTask = new CampaignTask();
			cTask.execute();
			
		    bTask = new BasketIdTask();
		    bTask.execute();
		}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		
		if (bTask != null)
			if (bTask.getStatus() == Status.RUNNING)
				bTask.cancel(true);
		
		if (cTask != null)
			if (cTask.getStatus() == Status.RUNNING)
				cTask.cancel(true);
		
		if (iTask != null)
			if (iTask.getStatus() == Status.RUNNING)
				iTask.cancel(true);
	}

	/*@Override
	public boolean onCreateOptionsMenu(android.view.Menu menu) {
		menu.add(android.view.Menu.NONE, -2, 0, "Info");
		menu.add(android.view.Menu.NONE, -1, 0, "Indstillinger");
		menu.add(android.view.Menu.NONE, 0, 0, "Genbestil ordre");
		for (int i = 0; i < cards.size(); i++)
			menu.add(android.view.Menu.NONE, cards.get(i).getIdx(), cards.get(i).getPosition() + 1, cards.get(i).getName());
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case -2:
			String version = "";
			try {
				PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0);
				version = info.versionName;
			} catch (NameNotFoundException e) { }
			Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://m.kyllingogco.dk/kontakt.asp?shopid=" + app.getShop().getIdx() + "&platform=Android&version=" + version));
			startActivity(browserIntent);
			break;
		case -1:
			Intent customer = new Intent(this, CustomerActivity.class);
			startActivity(customer);
			break;
		case 0:
			Intent order = new Intent(this, OrderActivity.class);
			startActivity(order);
			break;
		default:
			Intent card = new Intent(this, CardActivity.class);
			card.putExtra("idx", item.getItemId());
			card.putExtra("title", item.getTitle());
			startActivity(card);
			break;
		}
    	return true;
	}*/
	
	private class CampaignTask extends AsyncTask<Void, Void, Boolean> {
    	@Override
		protected Boolean doInBackground(Void... params) {
    		try {
    			InputStream in = Server.post(Server.CAMPAIGN, Server.getAuthenticationCampaign(context));
    			XmlPullParser parser = Server.toXmlParser(in);
    			campaign = XmlParser.getCampaign(parser);

    			Bitmap b = app.getBitmapFromMemCache(campaign.getBillede());
				if (b != null) {
					if (b.isRecycled()) {
						app.removeBitmapFromMemoryCache(campaign.getBillede());
						in = Server.get(Server.CAMPAIGN_IMAGES + campaign.getBillede());
		    			b = Server.downloadBitmap(in, (Activity)context);
					}
				} else {
					in = Server.get(Server.CAMPAIGN_IMAGES + campaign.getBillede());
	    			b = Server.downloadBitmap(in, (Activity)context);
				}
    			campaign.setImage(b);
    			app.addBitmapToMemoryCache(campaign.getBillede(), b);
    			
    			in.close();
    		} catch (IOException e) {
    			Log.e("Shop", "IOException: " + e.getMessage());
    			return false;
    		} catch (XmlPullParserException e) {
    			Log.e("Shop", "XmlPullParserException: " + e.getMessage());
    			return false;
    		} catch (NullPointerException e) {
    			Log.e("Shop", "NullPointerException: " + e.getMessage());
    			return false;
    		} catch (IllegalArgumentException e) {
    			Log.e("Shop", "IllegalArgumentException: " + e.getMessage());
    			return false;
    		}
    		return true;
    	}
    
	    @Override
	    protected void onPostExecute(Boolean success) {
	    	if (success && campaign != null) {
	    		image.setImageBitmap(campaign.getImage());
	    		header.setText(Html.fromHtml(campaign.getOverskrift().replace("\\n", "<br>").toUpperCase(Locale.ENGLISH)));
	    		text.setText(Html.fromHtml(campaign.getBesked().replace("\\n", "<br>")));
	    		obs.setText(Html.fromHtml(campaign.getObs().replace("\\n", "<br>")));
	    	}

			message.setText(getResources().getString(R.string.main_message));
			restaurant.setText(shop.getName());
			address.setText(shop.getAddress() + ", " + shop.getZipcode() + " " + shop.getCity());
			hours.setText(Html.fromHtml(getResources().getString(R.string.main_hours) + " <b>" + shop.getHours() + "</b>"));
			open.setText(Html.fromHtml(getResources().getString(R.string.main_open) + " <b>" + shop.getOrders() + "</b>"));
			proceed.setVisibility(View.VISIBLE);
			loading.dismiss();
	    }
	}
	
	private class BasketIdTask extends AsyncTask<Void, Void, Boolean> {
    	@Override
		protected Boolean doInBackground(Void... params) {
    		InputStream in;
			try {
				String telefon = preferences.getString("phone", "");
				in = Server.post(Server.BASKETID, Server.getAuthenticationBasketId(telefon, shop.getIdx()));
				XmlPullParser parser = Server.toXmlParser(in);
				basketId = XmlParser.getBasketId(parser);
			} catch (IOException e) {
    			Log.e("Shop", "IOException: " + e.getMessage());
				return false;
			} catch (XmlPullParserException e) {
    			Log.e("Shop", "XmlPullParserException: " + e.getMessage());
				return false;
			} catch (NullPointerException e) {
    			Log.e("Shop", "NullPointerException: " + e.getMessage());
    			return false;
    		} catch (IllegalArgumentException e) {
    			Log.e("Shop", "IllegalArgumentException: " + e.getMessage());
    			return false;
    		}
    		return true;
    	}
    	
    	@Override
	    protected void onPostExecute(Boolean success) {
    		if (success) {
    			app.setBasketId(basketId);
    		}
    	}
	}
	
	private class ImageTask extends AsyncTask<Integer, Void, Boolean> {
		private Bitmap b;
		
    	@Override
		protected Boolean doInBackground(Integer... params) {
    		try {
    			InputStream in = Server.get(Server.CAMPAIGN_IMAGES + shop.getPicture());
    			b = Server.downloadBitmap(in, (Activity)context);
    			in.close();
    			app.addBitmapToMemoryCache(shop.getPicture(), b);
			} catch (IOException e) {
    			Log.e("Shop", "IOException: " + e.getMessage());
				return false;
			} catch (NullPointerException e) {
    			Log.e("Shop", "NullPointerException: " + e.getMessage());
				return false;
			} catch (OutOfMemoryError e) {
    			Log.e("Shop", "OutOfMemoryError: " + e.getMessage());
				return false;
			}
    		return true;
    	}
    
	    @Override
	    protected void onPostExecute(Boolean success) {
			image.setImageBitmap(b);
	    	header.setText(R.string.main_closed);
			text.setText(shop.getClosed());
			loading.dismiss();
	    }
	}
	
	private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectItem(position);
        }
    }

    private void selectItem(int position) {
    	switch (position) {
		case 0:
			String version = "";
			try {
				PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0);
				version = info.versionName;
			} catch (NameNotFoundException e) { }
			Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://m.kyllingogco.dk/kontakt.asp?shopid=" + app.getShop().getIdx() + "&platform=Android&version=" + version));
			startActivity(browserIntent);
			break;
		case 1:
			Intent customer = new Intent(this, CustomerActivity.class);
			startActivity(customer);
			break;
		case 2:
			Intent order = new Intent(this, OrderActivity.class);
			startActivity(order);
			break;
		default:
			Intent card = new Intent(this, CardActivity.class);
			card.putExtra("idx", cards.get(position - 3).getIdx());
			card.putExtra("title", cards.get(position - 3).getName());
			startActivity(card);
			break;
		}
    	
        list.setItemChecked(position, false);
        layout.closeDrawer(list);
    }
}